<?php
/*
 * ebiz front
 *
 * CategoryController
 *
 * @author xiaoyuemian
 *
 */

require_once '../app/core/controllers/BaseController.php';
require_once '../app/core/utils/HttpUtil.class.php';
require_once '../app/views/BaseView.php';
require_once "../". $GLOBALS["local"] ."/"."category.php";
require_once "../". $GLOBALS["local"] ."/"."myaccount.php";

define('PRODUCTS_LIST_L1V2_PAGE_SIZE', 12);
define('PRODUCTS_LIST_L2V3_PAGE_SIZE', 16);

class CategoryControllerTest extends BaseController {

	public function index($param = array(), $bool_ajax = false){

		if(empty($param))
		    HttpUtil::renderError( 'Parameter Error' . __FILE__ . ':' . __LINE__ );
		//xiaoyuemian: 没从$param取url，直接从地址栏取的
//		$config = $GLOBALS["config"];
//        $urlTitle = urldecode($GLOBALS['config']['urlparam'][3]);
        //xiaoyuemian: param eg: [0]:women_costume [1]:page number(可选)
        $urlTitle = $param[0];
        array_shift($param);

        /*if($urlTitle != 'women_costume'){
        	$arr_param = array();
       		$arr_param['category'] = CategoryControllerTest::getIndexDataL1V1($urlTitle);
       		if( empty($arr_param['category']) )
       		    HttpUtil::renderError();
        	require_once '../app/views/CategoryView.php';
            $categoryFirstView = new CategoryFirstView();
            $categoryFirstView->addCSS('productlist.css');
            $categoryFirstView->addJs('class1.js');
            $str_content = $categoryFirstView->getCategoryFirstViewPage($arr_param);
            echo $str_content;
            exit();
        }else{*/
        	if($bool_ajax)
        	{
        		$arr_filter = CategoryControllerTest::getFilters($param);
        		$str_content = CategoryControllerTest::getIndexProductsContentL1V2($urlTitle, $arr_filter);
        		return $str_content;
        	}
        	else
        	{
        		$arr_filter = CategoryControllerTest::getFilters($param);
        		$str_content = CategoryControllerTest::getIndexContentL1V2($urlTitle, $arr_filter);
       			/*if( empty($str_content) )
       		    	HttpUtil::renderError();*/
        		echo $str_content;
        		exit();
        	}
        //}

	}
	
	protected function getFilters($arr_param)
	{
		$result = array();
		$arr_search = array();
    	$arr_sortby = array(
    	   'id' => 1, //default
    	   'price' => 0, //-1,0,1
    	   'created' => 0 //-1,0,1
    	);
    	$str_otherFilter = '';
    	$int_nowpage = 1;
    	    
		/**
	     * 参数形式为metadata_id,metadata_option_id,metadata_id,metadata_option_id...
	     */
	    if (!empty($arr_param)) {
	        $int_paramlength = count($arr_param);

	        for ($int_i=0; $int_i<$int_paramlength; $int_i+=2){
	            if (!empty($arr_param[$int_i]) && !empty($arr_param[$int_i+1])) {
	               if (strtolower($arr_param[$int_i])=='price') {
	                   $arr_sortby['price'] = $arr_param[$int_i+1];
	                   $arr_sortby['id'] = $arr_sortby['created'] = 0;
	               } elseif (strtolower($arr_param[$int_i])=='created') {
	                   $arr_sortby['created'] = $arr_param[$int_i+1];
	                   $arr_sortby['id'] = $arr_sortby['price'] = 0;
	               } elseif (strtolower($arr_param[$int_i])=='page') {
	                   $int_nowpage = $arr_param[$int_i+1];
	               } elseif (strtolower($arr_param[$int_i])=='money') {
	                   $arr_money = explode('-', $arr_param[$int_i+1]);
	                   $str_otherFilter .= " AND `pi`.`sale_price` >= '{$arr_money[0]}' ";
	                   if (isset($arr_money[1]))
	                        $str_otherFilter .= " AND `pi`.`sale_price` <= '{$arr_money[1]}' ";
	               } elseif(is_numeric($arr_param[$int_i])) {
	                   $arr_search['auto_metadata_' . $arr_param[$int_i]] = $arr_param[$int_i+1];
	               }
	            }
	        }
	    }
	    $result['sortby'] = $arr_sortby;
	    $result['nowpage'] = $int_nowpage;
	    $result['search'] = $arr_search;
	    $result['other'] = $str_otherFilter;
	    
	    return $result;
	}
	
	protected function getIndexDataL1V1($urlTitle)
	{
		require_once '../app/services/CategoryService.php';
		$categoryService = new CategoryService();
		$arr_selectCategoryData = $categoryService->getByUrlTitle($urlTitle);
		/*if( empty($arr_selectCategoryData[0] ) ){
            return;
		}*/
		//$arr_selectCategoryData = $arr_selectCategoryData[0];
		/*if(empty($arr_selectCategoryData)){
			return;
		}*/
		
		return $arr_selectCategoryData[0];
	}
	
	protected function getIndexContentL1V2($urlTitle = '', $arr_filter = array())
	{	
		if(empty($urlTitle))
		    return HttpUtil::renderError();;

		if(empty($arr_filter['nowpage']))
		    $int_nowpage = 1;
		else
            $int_nowpage = $arr_filter['nowpage'];
            

        if(empty($arr_filter['other']))
            $str_otherFilter = '';
        else
            $str_otherFilter = $arr_filter['other'];
        
        if(empty($arr_filter['sortby']))
            $arr_sortby = array(
    	       'id' => 1, //default
    	       'price' => 0, //-1,0,1
    	       'created' => 0 //-1,0,1
    	    );
    	else
            $arr_sortby = $arr_filter['sortby'];
            
        if(empty($arr_filter['search']))
            $arr_search = array();
        else
            $arr_search = $arr_filter['search'];
        
		require_once '../app/services/CategoryServiceTest.php';
		$categoryService = new CategoryServiceTest();
		$int_countrows = 0;
		$arr_productsInfo = $categoryService->getProductItemsByUrlTitleInCertainPage($urlTitle, $int_nowpage, PRODUCTS_LIST_L1V2_PAGE_SIZE, $int_countrows, $arr_sortby, $arr_search, $str_otherFilter);

		if( empty($arr_productsInfo) )
            return HttpUtil::renderError();
        
		$arr_products = $arr_productsInfo['products'];
		$arr_category = $arr_productsInfo['category'];
		
	    // sort, filter
	    $arr_navigation = $categoryService->getParentCategory($arr_category['id']);
	    //myt: nowpage and countrows are reference arguments
	    $arr_pager = array(
	       'nowpage' => $int_nowpage,
	       'countrows' => $int_countrows
	    );
	    
	    $arr_brands = $categoryService->getMetadataByTitleInCategoryId('品牌', $arr_category['id']);

	    $arr_metadatas = array(
	        '品牌' => $arr_brands
	        //'prices' => 
	    );
	    
	    require_once '../app/views/CategoryFirstViewL1V2.php';
        $categoryFirstView = new CategoryFirstViewL1V2();
        $categoryFirstView->m_category = $arr_category;
        $categoryFirstView->m_products = $arr_products;
        $categoryFirstView->m_pager = $arr_pager;
        $categoryFirstView->m_sortby = $arr_sortby;
        $categoryFirstView->m_navigation = $arr_navigation;
        $categoryFirstView->m_metadatas = $arr_metadatas;
        $categoryFirstView->m_filter = $str_otherFilter;        
        $str_content = $categoryFirstView->getCategoryFirstViewPageV2();
        
        return $str_content;
	}
	
	protected function getIndexProductsContentL1V2($urlTitle = '', $arr_filter = array())
	{	
		if(empty($urlTitle))
		    return HttpUtil::renderError();;

		if(empty($arr_filter['nowpage']))
		    $int_nowpage = 1;
		else
            $int_nowpage = $arr_filter['nowpage'];
            

        if(empty($arr_filter['other']))
            $str_otherFilter = '';
        else
            $str_otherFilter = $arr_filter['other'];
        
        if(empty($arr_filter['sortby']))
            $arr_sortby = array(
    	       'id' => 1, //default
    	       'price' => 0, //-1,0,1
    	       'created' => 0 //-1,0,1
    	    );
    	else
            $arr_sortby = $arr_filter['sortby'];
            
        if(empty($arr_filter['search']))
            $arr_search = array();
        else
            $arr_search = $arr_filter['search'];
        
		require_once '../app/services/CategoryServiceTest.php';
		$categoryService = new CategoryServiceTest();
		$int_countrows = 0;
		$arr_productsInfo = $categoryService->getProductItemsByUrlTitleInCertainPage($urlTitle, $int_nowpage, PRODUCTS_LIST_L1V2_PAGE_SIZE, $int_countrows, $arr_sortby, $arr_search, $str_otherFilter);

		if( empty($arr_productsInfo) )
            return HttpUtil::renderError();
        
		$arr_products = $arr_productsInfo['products'];
		$arr_category = $arr_productsInfo['category'];
		
    	require_once '../app/services/CategoryServiceTest.php';
	    $categoryService = new CategoryServiceTest();
	    // sort, filter
	    $arr_navigation = $categoryService->getParentCategory($arr_category['id']);
	    //myt: nowpage and countrows are reference arguments
	    $arr_pager = array(
	       'nowpage' => $int_nowpage,
	       'countrows' => $int_countrows
	    );
	    
	    require_once '../app/views/CategoryFirstViewL1V2.php';
        $categoryFirstView = new CategoryFirstViewL1V2();
        $categoryFirstView->m_category = $arr_category;
        $categoryFirstView->m_products = $arr_products;
        $categoryFirstView->m_pager = $arr_pager;
        $categoryFirstView->m_sortby = $arr_sortby;
        $categoryFirstView->m_navigation = $arr_navigation;
        //$categoryFirstView->m_metadatas = $arr_metadatas;
        $categoryFirstView->m_filter = $str_otherFilter; 
        $str_content = $categoryFirstView->getRightBlockProductsResult($arr_products, $arr_pager, $arr_sortby);
        
        return $str_content;
	}

	//$arr_param: url，第4级开始
	public function search($arr_param = array(), $bool_ajax = false){
	    /**
	     * 搜索条件处理
	     */
	    if ( empty( $arr_param[0] ) ){
	        HttpUtil::renderError( 'Parameter Error' . __FILE__ . ':' . __LINE__ );
	    }
	    $int_categoryid = array_shift($arr_param);
        $str_otherFilter = " AND `category_id` = '{$int_categoryid}'";
        
        $urlDecodeResult = CategoryControllerTest::getFilters($arr_param);
        $int_nowpage = $urlDecodeResult['nowpage'];
        $arr_search = $urlDecodeResult['search'];
        $arr_sortby = $urlDecodeResult['sortby'];
        $str_otherFilter .= $urlDecodeResult['other'];

	    /**
	     * @desc 分页设置
	     */
	    $int_countrows = 0;
	    require_once '../app/services/CategoryServiceTest.php';
	    $categoryService = new CategoryServiceTest();
	    $arr_navigation = $categoryService->getParentCategory($int_categoryid);
	    $arr_categoryChildren = $categoryService->getCategoryChildren($int_categoryid);
	    //$arr_categorySiblings = $categoryService->getCategoryChildren($arr_navigation[0]['parent_id']);
	    $arr_metadatas = $categoryService->getMeatadatasByCategoryId($int_categoryid);
	    if(empty($arr_metadatas))
	        $arr_products = $categoryService->getProductsByParentCategoryId($int_categoryid, $int_nowpage, PRODUCTS_LIST_L2V3_PAGE_SIZE, $int_countrows, $arr_sortby, $arr_search, $urlDecodeResult['other']);
	    else
    	    $arr_products = $categoryService->getProductItemsByCategoryId($int_nowpage, PRODUCTS_LIST_L2V3_PAGE_SIZE, $int_countrows, $int_categoryid, $arr_search, $arr_sortby, $str_otherFilter);
	    //myt: nowpage and countrows are reference arguments
	    $arr_pager = array(
	       'nowpage' => $int_nowpage,
	       'countrows' => $int_countrows, 
	       'pagesize' => PRODUCTS_LIST_L2V3_PAGE_SIZE
	    );

	    require_once '../app/views/CategorySearchViewL2V3.php';
	    $categorySearchView = new CategorySearchViewL2V3();
	    $categorySearchView->category_id = $int_categoryid;
	    $categorySearchView->metadatas = $arr_metadatas;
	    $categorySearchView->products = $arr_products;
	    $categorySearchView->pager = $arr_pager;
	    $categorySearchView->sort = $arr_sortby;
	    $categorySearchView->filter = $arr_search;
	    $categorySearchView->navigation = $arr_navigation;
	    $categorySearchView->categoryChildren = $arr_categoryChildren;
	    //$categorySearchView->categorySiblings = $arr_categorySiblings;
	    if( !$bool_ajax )
	       echo $categorySearchView->getPage();
	    else
	       return $categorySearchView->getSearchResultBlock();
	    exit;
	}

}


